import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
	state:{
		shopCarlist : [],
		shopCarLength : 0,
	},
	mutations:{
		addShopCar(state , Sitem){
			//console.log(Sitem)
			//console.log(state.shopCarlist)
			let flag = false; //默认购物车不存在该商品
			let idx = -1 ;//商品在购物车的下标
			for (var i = 0; i < state.shopCarlist.length; i++) {
				if (state.shopCarlist[i].id == Sitem.id) { //如果id存在就说明存在
					flag = true;
					idx = i;
					break; //退出循环
				}
			}
			if (!flag) { //如果不存在才需要push
				Sitem.num = 0;
				Sitem.num++;
				state.shopCarlist.push(Sitem)
			}else{//存在就不用push，只改变num
				state.shopCarlist[i].num++;
				state.shopCarlist = [...state.shopCarlist];
			}
			
		},
		deleteShopCar(state,Sitem){ // 垃圾桶符号，点击删除该商品
			state.shopCarlist.pop(Sitem)
		},
		Sitemjia(state , Sitem){ // 加号  点击添加商品数量
			for(var i = 0 ; i < state.shopCarlist.length ; i++){
				if(state.shopCarlist[i].id == Sitem.id){
					// state.shopCarlist[i] = { ...state.shopCarlist[i], num: state.shopCarlist[i].num+1}
					state.shopCarlist[i].num++;
					state.shopCarlist = [...state.shopCarlist]; //合并数组：改变了num属性后与原本数组合并
					break;
				}
			}
		},
		Sitemjan(state ,Sitem){ //减号 点击减去产品数量  小于0则删除商品
			for(var i = 0 ; i < state.shopCarlist.length ; i++){
				if(state.shopCarlist[i].id == Sitem.id){
					if( state.shopCarlist[i].num > 1 ){
						state.shopCarlist[i] = {...state.shopCarlist[i], num: state.shopCarlist[i].num-1}
						state.shopCarlist = [...state.shopCarlist]
						break;
					}else{
						state.shopCarlist.pop(Sitem)
					}
				}
			}
		}
	},
	getters:{
		getCarList(state){ // 返回购物车商品总数组长度
			return state.shopCarlist.length
		},
		getCarlistPrice(state){ // 返回购物车商品总价钱
			var addprice = 0;
			for(var i = 0 ; i < state.shopCarlist.length ; i++){
				 addprice = addprice + state.shopCarlist[i].money*state.shopCarlist[i].num 
			}
			return addprice
		},
		getCarlistAdnum(state){ // 返回购物车总件数
			var Adnum = 0;
			for(var i = 0 ; i < state.shopCarlist.length ; i++){
				 Adnum = Adnum + state.shopCarlist[i].num 
			}
			return Adnum
		},
	}
})